package ink.liaoxuefeng.javacore;

import java.util.StringJoiner;

/**
 * @author wangzhuangzhuang
 * @DESC: 要高效拼接字符串，应该使用StringBuilder
 * @date 2022-01-25 10:37
 */
public class StringJoinerDemo {

	public static void main(String[] args) {
		System.out.println("===================StringBuilder进行拼接====================");
		String[] names = {"Bob", "Alice", "Grace"};
		StringBuilder sb = new StringBuilder();
		sb.append("Hello ");
		for(String name : names){
			sb.append(name).append(", ");
		}
		// 注意去掉最后的", ";
		sb.delete(sb.length() - 2,sb.length());
		sb.append("!");
		System.out.println(sb.toString()); // Hello Bob, Alice, Grace!
		System.out.println("===================StringJoiner进行拼接======================");
		String[] names01 = {"Bob", "Alice", "Grace"};
		StringJoiner sj = new StringJoiner(", ");
		for(String name : names){
			sj.add(name);
		}
		System.out.println(sj.toString()); // Bob, Alice, Grace

		StringJoiner hello_ = new StringJoiner(", ", "Hello ", "!");
		for(String name : names){
			hello_.add(name);
		}
		System.out.println(hello_.toString()); // Hello Bob, Alice, Grace!
		System.out.println("===================String.join()拼接======================");
		/**
		 * String提供一个静态方法join()，这个方法在内部使用了StringJoiner来拼接字符串，在不需要指定“开头”和“结尾”的时候
		 * 用String.join()更为方面
		 * */
		String[] names02 = {"Bob", "Alice", "Grace"};
		System.out.println("joinedNames01: " + String.join(",", names02).toString()); // joinedNames01: Bob,Alice,Grace
	}
}
